from flask import Blueprint, render_template, request
from flask_login import login_required, current_user
from sqlalchemy import desc

from applications.common import curd
from applications.common.curd import model_to_dicts, enable_status, disable_status
from applications.common.helper import ModelFilter
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import xss_escape
# from applications.models.admin_scenetrain import TrainType

from applications.extensions import db
from applications.models import Role

from applications.models import TrainType, AdminLog
from applications.schemas import UserOutSchema,TrainOutSchema

admin_atkdef_scene = Blueprint('adminAatkdefSe', __name__, url_prefix='/admin/atkdef_scene')



# 训练项管理
@admin_atkdef_scene.get('/')
@authorize("atkdef_scene:info", log=True)
def main():
    return render_template('admin/atkdef_scene/atkdef.html')

#   训练项分页查询
@admin_atkdef_scene.get('/data')
@authorize("atkdef_scene:info", log=True)
def data():
    # 获取请求参数
    traintype = xss_escape(request.args.get('train_type', type=str))

    # 查询参数构造
    mf = ModelFilter()
    if traintype:
        mf.contains(field_name="train_type", value=traintype)
    # orm查询
    # 使用分页获取data需要.items
    train = TrainType.query.filter(mf.get_filter(model=TrainType)).layui_paginate()
    count = train.total
    # 返回api
    return table_api(data=model_to_dicts(schema=TrainOutSchema, data=train.items), count=count)


# 训练项增加
@admin_atkdef_scene.get('/add')
@authorize("atkdef_scene:add", log=True)
def add():
    trains = TrainType.query.with_entities(TrainType.scene_type).distinct().all()

    return render_template('admin/atkdef_scene/add.html', trains = trains)

# 训练项增加
@admin_atkdef_scene.post('/save')
@authorize("atkdef_scene:add", log=True)
def save():
    req_json = request.json
    a = req_json.get("roleIds")
    traintype = xss_escape(req_json.get('train_type'))
    if not req_json.get("roleIds"):
        scenetype = xss_escape(req_json.get('scene_type'))
    else:
        scenetype = xss_escape(req_json.get('roleIds'))
    # password = xss_escape(req_json.get('password'))/
    role_ids = a.split(',')

    if not traintype or not scenetype:
        return fail_api(msg="训练项名称和情景名称不得为空")

    if bool(TrainType.query.filter_by(train_type=traintype).count()):
        return fail_api(msg="训练项已经存在")
    train = TrainType(train_type=traintype, scene_type=scenetype)

    db.session.add(train)
    db.session.commit()
    return success_api(msg="增加成功")


# 删除训练项
@admin_atkdef_scene.delete('/remove/<int:id>')
@authorize("atkdef_scene:remove", log=True)
def delete(id):

    res = TrainType.query.filter_by(id=id).delete()
    db.session.commit()
    if not res:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")


#  编辑训练项
@admin_atkdef_scene.get('/edit/<int:id>')
@authorize("atkdef_scene:edit", log=True)
def edit(id):
    train = curd.get_one_by_id(TrainType, id)
    trains = TrainType.query.with_entities(TrainType.scene_type).distinct().all()
    # checked_roles = []
    # for r in user.role:
    #     checked_roles.append(r.id)
    return render_template('admin/atkdef_scene/edit.html', train=train, trains = trains)


#  编辑训练项
@admin_atkdef_scene.put('/update')
@authorize("atkdef_scene:edit", log=True)
def update():
    req_json = request.json
    id = xss_escape(req_json.get("trainId"))
    traintype = xss_escape(req_json.get('train_type'))
    if not req_json.get("roleIds"):
        scenetype = xss_escape(req_json.get('scene_type'))
    else:
        scenetype = xss_escape(req_json.get('roleIds'))

    if not traintype or not scenetype:
        return fail_api(msg="训练项名称和情景名称不得为空")


    TrainType.query.filter_by(id=id).update({'train_type': traintype, 'scene_type': scenetype})
    db.session.commit()
    return success_api(msg="更新成功")


# 启用训练项
@admin_atkdef_scene.put('/enable')
@authorize("atkdef_scene:edit", log=True)
def enable():
    _id = request.json.get('trainId')
    if _id:
        res = enable_status(model=TrainType, id=_id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="启动成功")
    return fail_api(msg="数据错误")


# 禁用训练项
@admin_atkdef_scene.put('/disable')
@authorize("atkdef_scene:edit", log=True)
def dis_enable():
    _id = request.json.get('trainId')
    if _id:
        res = disable_status(model=TrainType, id=_id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="禁用成功")
    return fail_api(msg="数据错误")


# 批量删除
@admin_atkdef_scene.delete('/batchRemove')
@authorize("atkdef_scene:remove", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')
    for id in ids:
        res = TrainType.query.filter_by(id=id).delete()
        db.session.commit()
    return success_api(msg="批量删除成功")
